<?php
//后台用户管理
namespace App\Http\Controllers\Admin;

use App\Models\Role;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Mail\Message;
use Mail;

//验证加密的密码的明文
use Hash;

class UserController extends BaseController
{
    //用户列表
    public function index(Request $request)
    {
        $kw = $request->input('kw', '');
        $stime = $request->input('stime', '');
        $etime = $request->input('etime', '');
        //分页   withTrashed  显示所有的，包括已经软删除的数据
        \DB::connection()->enableQueryLog();
        $data = User::when($kw, function ($query) use ($kw) {
            $query->where(function ($query) use ($kw) {
                $query->where('username', $kw);
            })->orWhere(function ($query) use ($kw) {
                $query->where('email', $kw);
            })->orWhere(function ($query) use ($kw) {
                $query->where('phone', $kw);
            });
        })->when($stime,function ($query) use ($stime,$etime){
            $query->whereBetween('created_at',[$stime.' 00:00:00',$etime.' 23:59:59']);
        })->withTrashed()->paginate($this->pagesize);
        print_r(\DB::getQueryLog());
        return view('admin.user.index', compact('data','kw','stime','etime'));
    }

    //添加显示
    public function create()
    {
        return view('admin.user.create');

    }

    //添加处理
    public function store(Request $request)
    {
//        $this->validate($request,[
//            'username'=>'required',
//            'truename'=>'required',
//            'password'=>'required|confirmed',
//            'phone'=>'nullable|phone',
//        ],[
//            'phone.phone'=>'手机异常',
//        ]);
        $this->validate($request, [
            'username' => 'required|unique:users,username',  //用户名唯一性验证
            'truename' => 'required',
            'password' => 'required|confirmed', //两次密码是否一致的验证
            'phone' => 'nullable|phone',
        ]);
        //添加用户入库
        $userModel = User::create($request->except(['_token', 'password_confirmation']));
        //密码
        $pwd = $request->input('password');
        //发邮件给用户
        Mail::send('mail.useradd', compact('userModel', 'pwd'), function (Message $message) use ($userModel) {
            //发给谁
            $message->to($userModel->email);
            //主题
            $message->subject('开通账号邮件通知');
        });
        //跳转到列表页
        return redirect(route('admin.user.index'))->with('success', '添加用户成功');

    }

    //删除用户
    public function del(int $id)
    {
        User::find($id)->delete();  //启用软删除
        //强制删除 在配置了软删除的时候，真实的删除
//        User::find($id)->forceDelete();
        return ['status' => 0, 'msg' => '删除成功'];
    }

    //还原
    public function restore(int $id)
    {
        User::onlyTrashed()->where('id', $id)->restore();
        return redirect(route('admin.user.index'))->with('success', '还原用户成功');
    }

    //全选删除
    public function delall(Request $request)
    {
        $ids = $request->get('id');
        User::destroy($ids);
        return ['status' => 0, 'msg' => '全选删除成功'];
    }

    //修改显示
    public function edit(int $id)
    {
        $model = User::find($id);
        return view('admin.user.edit', compact('model'));
    }

    //修改处理
    public function update(Request $request, int $id)
    {
        $model = User::find($id);
        $spass = $request->input('spassword');
        //检查明文密文密码是否一致
        $bool = Hash::check($spass, $model->password);
        if ($bool) {
            //修改
            $data = $request->only([
                'truename',
                'password',
                'sex',
                'phone',
                'email'
            ]);
            if (!empty($data['password'])) {
                $data['password'] = bcrypt($data['password']);
            } else {
                unset($data['password']);
            }
            $model->update($data);
            return redirect(route('admin.user.index'))->with(['success' => '修改成功']);
        }
        return redirect(route('admin.user.edit', $model))->withErrors(['error' => '原密码不正确']);
    }

    //分配角色和处理
    public function role(Request $request, User $user)
    {
        //判断是否是Post提示
        if ($request->isMethod('post')) {
            $post = $this->validate($request, [
                'role_id' => 'required'
            ], ['role_id.required' => '必选']);
            $user->update($post);
            return redirect(route('admin.user.index'));
        }


        $roleAll = Role::all();
        return view('admin.user.role', compact('roleAll', 'user'));
    }
}
